/**
 * @filename:ExportModelConfigController 2023-11-12 08:11:06
 * @project com/lwl/blue  V1.0
 * Copyright(c) 2020 <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a> Co. Ltd.
 * All right reserved.
 */
package com.lwl.blue.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lwl.blue.commont.base.*;
import com.lwl.blue.commont.enums.FileUploadTypeEnum;
import com.lwl.blue.commont.enums.SourceTypeEnum;
import com.lwl.blue.commont.utils.ExcelTemplateUtil;
import com.lwl.blue.commont.utils.FileUtils;
import com.lwl.blue.commont.utils.ParamsCheckUtilService;
import com.lwl.blue.commont.utils.UserContextUtil;
import com.lwl.blue.entity.Customer;
import com.lwl.blue.entity.ExportModelConfig;
import com.lwl.blue.entity.Files;
import com.lwl.blue.service.ExportModelConfigService;
import com.lwl.blue.service.FilesService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * <p>自定义方法写在这里</p>
 *
 * <p>说明： 导出模板配置表API接口层</P>
 *
 * @version: V1.0
 * @author: <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a>
 */
@Api(tags = "导出模板配置表")
@RestController
@RequestMapping("/exportModelConfig")
@Slf4j
public class ExportModelConfigController extends BaseController {
    @Resource
    ExportModelConfigService exportModelConfigService;
    @Value("${upload.filePath}")
    private String filePath;
    @Value("${export.file.path.prefix}")
    private String prefix;

    @PostMapping("/pages")
    public PageResult<ExportModelConfig> getPages(@RequestBody PageParam<ExportModelConfig> pageParam) {
        JsonResult<Page<ExportModelConfig>> pages = exportModelConfigService.pages(pageParam);
        PageResult<ExportModelConfig> re = new PageResult<>();
        re.success(pages.getData().getTotal(), pages.getData().getRecords());
        return re;
    }

    @PostMapping("saveOrUpdate")
    public JsonResult saveOrUpdate(@RequestBody @Valid ExportModelConfig exportModelConfig) {
        setInsetOrUpdateUser(exportModelConfig);
        QueryWrapper<ExportModelConfig> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ExportModelConfig::getIsDelete, Const.IS_DELETE_NO);
        wrapper.lambda().eq(ExportModelConfig::getType, exportModelConfig.getType());
        wrapper.lambda().eq(ExportModelConfig::getSupplierId,exportModelConfig.getSupplierId());
        wrapper.lambda().eq(ExportModelConfig::getCustomerId,exportModelConfig.getCustomerId());
        if (null != exportModelConfig.getId()) {
            wrapper.lambda().notIn(ExportModelConfig::getId, exportModelConfig.getId());
        }
        int count = exportModelConfigService.count(wrapper);
        if (count > 0) {
            throw new BizException(ErrorCode.DATA_EXISTS_ERROR.getCode(), ErrorCode.DATA_EXISTS_ERROR.getMsg() + exportModelConfig.getId());
        }
        exportModelConfigService.saveOrUpdate(exportModelConfig);
        return new JsonResult().success("请求成功");
    }

    @PostMapping("/delete/{id}")
    public JsonResult saveOrUpdate(@PathVariable(value = "id") Integer id) {
        exportModelConfigService.update(new UpdateWrapper<ExportModelConfig>().lambda()
                .set(ExportModelConfig::getIsDelete, Const.IS_DELETE_YES)
                .set(ExportModelConfig::getUpdateUser, UserContextUtil.getUser().getUserName())
                .eq(ExportModelConfig::getId, id));
        return new JsonResult().success("请求成功");
    }

    @PostMapping("/select/{type}")
    public JsonResult select(@PathVariable(value = "type") String type) {
        List<ExportModelConfig> reList = exportModelConfigService.list(new QueryWrapper<ExportModelConfig>()
                .lambda().eq(ExportModelConfig::getIsDelete, Const.IS_DELETE_NO)
                .eq(ExportModelConfig::getType,type));
        return new JsonResult().success(reList);
    }

    /**
     * 报价单导出模板文件上传
     *
     * @param uploadFile
     * @param id
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/uploadFile/{id}", method = RequestMethod.POST)
    private JsonResult uploadFile(@RequestParam("file") MultipartFile uploadFile, @PathVariable(value = "id") Integer id) {
        InputStream inputStream = null;
        String reMessage = "上传成功";
        String fileName = id + ".xlsx";
        ExportModelConfig data = exportModelConfigService.getById(id);
        String secondHalf = FileUploadTypeEnum.EXPORT.getType() + "/"+data.getType()+"/" + fileName;
        String file = filePath + secondHalf;
        try {
            //判断文件是否存在
            File upFile = new File(file);
            //文件存在
            if (upFile.exists()) {
                reMessage = "文件已存在，替换成功";
            }
            inputStream = uploadFile.getInputStream();
            //保存文件
            FileUtils.upload(file, uploadFile);
        } catch (IOException e) {
            log.error("文件上传异常：{}，异常信息：{}", e, e.getMessage());
            return new JsonResult().error(e.getMessage());
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("文件上传关闭异常：{}，异常信息：{}", e, e.getMessage());
                }
            }
        }
        //新增
        String filePath = prefix + secondHalf;
        exportModelConfigService.update(new UpdateWrapper<ExportModelConfig>().lambda()
                .set(ExportModelConfig::getUrl, filePath)
                .set(ExportModelConfig::getUpdateUser, UserContextUtil.getUser().getUserName())
                .set(ExportModelConfig::getUpdateTime, new Date())
                .eq(ExportModelConfig::getId, id));
        //转换成可以直接访问的地址
        JsonResult re = new JsonResult().success(reMessage);
        re.setData(filePath);
        return re;
    }

}